package com.jy.wms.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.*;
import com.jy.wms.dao.*;
import com.jy.wms.pojo.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
    * @ClassName: WmsEstimatedArrivalOrderService.java
    * @Description: TODO(这里用一句话描述这个类的作用)
    * @Author Liyi
    * @Date Wed Sep 27 09:24:27 CST 2017
    */

    @Service
    public class WmsEstimatedArrivalOrderService extends BaseService<WmsEstimatedArrivalOrderMapper,WmsEstimatedArrivalOrder> {

    @Autowired
    private WmsEstimatedArrivalOrderDetailedMapper wmsEstimatedArrivalOrderDetailedMapper;

    @Autowired
    private WmsPurchaseOrderMapper wmsPurchaseOrderMapper;

    @Autowired
    private WmsPurchaseOrderDetailedMapper wmsPurchaseOrderDetailedMapper;

    @Autowired
    private WmsPackingDetailedMapper wmsPackingDetailedMapper;

    @Autowired
    private WmsOwnerMapper wmsOwnerMapper;

    @Autowired
    private WmsOwnerOrdertypeMapper wmsOwnerOrdertypeMapper;
    @Autowired
    private WmsQualityInspectionListMapper wmsQualityInspectionListMapper;
    @Autowired
    private WmsQualityInspectionListDetailedMapper wmsQualityInspectionListDetailedMapper;
    @Autowired
    private WmsReceiptTaskPdaMapper wmsReceiptTaskPdaMapper;
    @Autowired
    private WmsReceiptTaskPdaDetailedMapper wmsReceiptTaskPdaDetailedMapper;

     /**
     * 插入一条记录
     * @param entity 实体对象
     * @return int
     */
    public Integer baseInsert( WmsEstimatedArrivalOrder entity){
         return dao.baseInsert( entity );
    }

    /**
     * 插入一条记录（匹配有值的字段）
     * @param entity 实体对象
     * @return int
     */
    @Transactional
    @BaseServiceDescribe(moduleName = "预期到货通知单",btnName = "新增预期到货通知单")
    public void baseInsertSelective( WmsEstimatedArrivalOrder entity ) throws ServiceException,SucessException{
        //判断ASN编号是否重复
        if(dao.getCountByAsnbh(entity.getAsnbh()) <= 0 ){
            //判断乐观锁 改数据是否已经被其他人操作
            Long locking = entity.getLocking();
            Long lockingDb = 0L;
            if(entity.getDycgdid() != null){
                lockingDb =  dao.getLocking(entity.getDycgdid());
                entity.setPobh(wmsPurchaseOrderMapper.baseSelectByPrimaryKey(entity.getDycgdid()).getBh());
            }
            //判断如果 锁不等于-1 则启用锁 如果>=0 则启用锁
            if(locking == -1 || locking > lockingDb){
                //判断如果选择的asn类型是否自动审核  如果自动审核则生成的ASN审核状态为 审核
                WmsOwnerOrdertype wmsOwnerOrdertype = wmsOwnerOrdertypeMapper.selectById(entity.getAsnlx());
                if(wmsOwnerOrdertype.getZdsh().equals("1")){
                    entity.setShzt("1");
                }
                Integer addCount = dao.baseInsertSelective( entity );
                List<WmsEstimatedArrivalOrderDetailed> list = entity.getDetailed();
                //遍历明细 赋值ID  赋值时间转换 备注如果没有传入则给空字符
                if(list != null && list.size()>0){
                    StringBuffer yqxsl = new StringBuffer("");
                    for (WmsEstimatedArrivalOrderDetailed wmsEstimatedArrivalOrderDetailed : list) {
                        wmsEstimatedArrivalOrderDetailed.setSsyqdid(entity.getId());
                        wmsEstimatedArrivalOrderDetailed.setHzid(entity.getHzid());
                        wmsEstimatedArrivalOrderDetailed.setId(UUIDUtils.uuid());
                        wmsEstimatedArrivalOrderDetailed.setCkid(entity.getCkid());
                        if(wmsEstimatedArrivalOrderDetailed.getJe() == null){
                            wmsEstimatedArrivalOrderDetailed.setJe(new BigDecimal("0.00"));
                        }
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        wmsEstimatedArrivalOrderDetailed.setScrq(formatter.format(new Date(Long.valueOf(wmsEstimatedArrivalOrderDetailed.getScrq()))));
                        if(wmsEstimatedArrivalOrderDetailed.getSxrq() !=null && !wmsEstimatedArrivalOrderDetailed.getSxrq().equals("")){
                            wmsEstimatedArrivalOrderDetailed.setSxrq(formatter.format(new Date(Long.valueOf(wmsEstimatedArrivalOrderDetailed.getSxrq()))));
                        }
                        wmsEstimatedArrivalOrderDetailed.setSsyqdid(entity.getId());
                        if(wmsEstimatedArrivalOrderDetailed.getBz() == null){
                            wmsEstimatedArrivalOrderDetailed.setBz("");
                        }
                        //计算箱单位数量
                        String str = dao.getCountByZdw(wmsEstimatedArrivalOrderDetailed.getZdwid());
                        Integer count = str == null ? Integer.MAX_VALUE : Integer.valueOf(str);
                        Double zsl = Double.valueOf(wmsEstimatedArrivalOrderDetailed.getYqsl());
                        yqxsl.append((int)(zsl/count)+"箱");
                        yqxsl.append((int)(zsl%count)+"件");
                        wmsEstimatedArrivalOrderDetailed.setYqxsl(yqxsl.toString());
                        //清空StringBuffer
                        yqxsl.setLength(0);
                    }
                    wmsEstimatedArrivalOrderDetailedMapper.baseInsertAll(list);
                    Map<String,Object> lockMap = new HashMap<String,Object>();
                    lockMap.put("locking",locking);
                    lockMap.put("id",entity.getDycgdid());
                    dao.setLocking(lockMap);
                    if(addCount>0){
                        throw new SucessException("新增预期到货通知单成功");
                    }else{
                        throw new ServiceException("新增预期到货通知单失败，未插入数据库");
                    }
                }
            }else{
                throw new ServiceException("新增预期到货通知单失败，此单已被其他用户提取，请重新操作");
            }
        }else{
            throw new ServiceException("新增预期到货通知单失败，ASN编号重复");
        }
    }

   /**
    * 删除（根据主键ID删除）
    * @param id 主键
    * @return int
    */
    public Integer baseDeleteByPrimaryKey( String id ){
         return dao.baseDeleteByPrimaryKey( id );
    }

   /**
    * 删除（根据ID 批量删除）
    * @param idList 主键ID列表
    * @return int
    */
    public Integer baseDeleteBathPrimaryKeys( List<String> idList ){
         return dao.baseDeleteBathPrimaryKeys( idList );
    }

        /**
         * 分页查询
         * @param entity 实体
         * @return Page<WmsEstimatedArrivalOrder>
         */
        @BaseServiceDescribe(moduleName = "预期到货通知单",btnName = "查询预期到货通知单列表")
        public Page<WmsEstimatedArrivalOrder> baseSelectPage(WmsEstimatedArrivalOrder entity, String hzid, String ssckid,String ckmc,String hzmc) throws Exception{
            try {
                String cjsj_start="";
                String cjsj_end="";
                PageHelper.startPage(entity.getPage(),entity.getRows());
                if(entity.getCjsj_start() !=0 && entity.getCjsj_end() !=0){
                    SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    cjsj_start = sdf.format(new Date(entity.getCjsj_start()));
                    cjsj_end = sdf.format(new Date(entity.getCjsj_end()));
                }
                Page<WmsEstimatedArrivalOrder> list = (Page<WmsEstimatedArrivalOrder>)dao.baseSelectPage( entity,hzid,ssckid,cjsj_start,cjsj_end,ckmc,hzmc);
//                for (WmsEstimatedArrivalOrder wmsEstimatedArrivalOrder : list) {
//                    List<WmsEstimatedArrivalOrderDetailed> detailedList = wmsEstimatedArrivalOrderDetailedMapper.baseSelectBySsyqdid(wmsEstimatedArrivalOrder.getId());
//                    wmsEstimatedArrivalOrder.setDetailed(detailedList);
//                }
                return list;
            } catch (Exception e) {
                throw new ServiceException("查询预期到货通知单列表",e);
            }
        }
    /**
     * 码盘分页查询
     * @param entity 实体
     * @return Page<WmsEstimatedArrivalOrder>
     */
    @BaseServiceDescribe(moduleName = "码盘收货查询",btnName = "查询码盘收货列表")
    public Page<WmsEstimatedArrivalOrder> seachSorting(WmsEstimatedArrivalOrder entity, String hzid, String ssckid,String ckmc ) throws Exception{
        try {
            String cjsj_start="";
            String cjsj_end="";
            PageHelper.startPage(entity.getPage(),entity.getRows());
            if(entity.getCjsj_start() !=0 && entity.getCjsj_end() !=0){
                SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                cjsj_start = sdf.format(new Date(entity.getCjsj_start()));
                cjsj_end = sdf.format(new Date(entity.getCjsj_end()));
            }
            return (Page<WmsEstimatedArrivalOrder>)dao.seachSorting( entity,hzid,ssckid,cjsj_start,cjsj_end,ckmc);
        } catch (Exception e) {
            throw new ServiceException("查询码盘收货列表",e);
        }
    }
    /**
     * ASN分页查询
     * @param entity 实体
     * @return Page<WmsEstimatedArrivalOrder>
     */
    @BaseServiceDescribe(moduleName = "ASN收货查询",btnName = "查询ASN收货查询列表")
    public Page<WmsEstimatedArrivalOrder> seachASNReceiving(WmsEstimatedArrivalOrder entity, String hzid, String ssckid,String ckmc ) throws Exception{
        try {
            String cjsj_start="";
            String cjsj_end="";
            PageHelper.startPage(entity.getPage(),entity.getRows());
            if(entity.getCjsj_start() !=0 && entity.getCjsj_end() !=0){
                SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                cjsj_start = sdf.format(new Date(entity.getCjsj_start()));
                cjsj_end = sdf.format(new Date(entity.getCjsj_end()));
            }
            return (Page<WmsEstimatedArrivalOrder>)dao.seachASNReceiving( entity,hzid,ssckid,cjsj_start,cjsj_end,ckmc);
        } catch (Exception e) {
            throw new ServiceException("查询ASN收货查询列表",e);
        }
    }

    @BaseServiceDescribe(moduleName = "预期到货通知单",btnName = "新增查询供应商编号及预计到货时间")
    public Map<String,Object> getGysAndYjsj(String sscgdid) throws Exception{
        try {
            Map<String,Object> map = dao.getGysAndYjsj(sscgdid);
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar c = Calendar.getInstance();
            Timestamp time = (Timestamp)map.get("yjdhsjks");
            c.setTime(new Date(time.getTime()));
            c.add(Calendar.DAY_OF_MONTH, 1);
            map.put("yjdhsjjs",sdf.format(c.getTime()));
            map.put("yjdhsjks",sdf.format(time));
            //赋予乐观锁值
            map.put("locking",dao.getLocking(sscgdid)+1);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("新增查询供应商编号及预计到货时间失败",e);
        }
    }

        /**
         * 分页查询PO编号列表
         * @param page 当前页
         * @param  rows 每页显示行数
         * @return Page<WmsEstimatedArrivalOrder>
         */
        @BaseServiceDescribe(moduleName = "预期到货通知单",btnName = "分页查询PO编号列表")
        public Page<Map<String,Object>> baseSelectPurchaseOrderPage(Integer page, Integer rows, String bh,String hzid,String ckmc)throws Exception{
            try {
                PageHelper.startPage(page,rows);
                return (Page<Map<String,Object>>)dao.baseSelectPurchaseOrderPage(bh,hzid,ckmc);
            } catch (Exception e) {
                throw new ServiceException("分页查询PO编号列表",e);
            }
        }

        /**
         * 分页查询PO明细列表
         * @return Page<WmsEstimatedArrivalOrder>
         */
        @BaseServiceDescribe(moduleName = "预期到货通知单",btnName = "分页查询PO明细列表")
        public List<Map<String,Object>> getPoDetailed(String sscgdid)throws Exception{
            try {
                List<Map<String,Object>> list = dao.getPoDetailed(sscgdid);
                //计算箱单位数量
                StringBuffer yqxsl = new StringBuffer("");
                for (Map<String, Object> stringObjectMap : list) {
                    String str = dao.getCountByZdw(stringObjectMap.get("zdwid").toString());
                    Integer count = str == null ? Integer.MAX_VALUE : Integer.valueOf(str);
                    Double zsl = Double.valueOf(stringObjectMap.get("yqsl").toString());
                    yqxsl.append((int)(zsl/count)+"箱");
                    yqxsl.append((int)(zsl%count)+"件");
                    stringObjectMap.put("xdwsl",yqxsl.toString());
                    //清空StringBuffer
                    yqxsl.setLength(0);
                }
                return list;
            } catch (Exception e) {
                throw new ServiceException("分页查询PO明细列表",e);
            }
        }

        /**
         * 查询所有类型为“入库单”的收发类别
         * @param hzid 货主ID
         * @return
         */
        @BaseServiceDescribe(moduleName = "预期到货通知单",btnName = "查询所有类型为“入库单”的收发类别")
        public Map<String,Object> getOrderType(String hzid) throws Exception{
            try {
                return dao.getOrderType(hzid);
            } catch (Exception e) {
                throw new ServiceException("查询所有类型为“入库单”的收发类别",e);
            }
        }

    @BaseServiceDescribe(moduleName = "预期到货通知单",btnName = "获取新增需要的信息 id:采购订单ID")
    public JSONObject getInfoByPo(SetAndModifyModel setAndModifyModel, String ckmc,JSONObject json, List<SysHz> hz,String zdr) throws Exception{
        try {
            String dycgdid = setAndModifyModel.getId();
            //查询采购订单对应的预期到货通知单是否存在 如果存在则
            Map<String,Object> map = dao.baseSelectByPrimaryDcgdid(dycgdid);
            if(map != null){
                json = JSONObject.fromObject(map);
            }else{
                //插入默认信息
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
                String asnbh = df.format(new Date())+Integer.toString((int)(Math.random()*9+1)*1000);
                json.put("asnbh",asnbh);
                json.put("asnzt",0);
                json.put("yxj",1);
                json.put("zjzt",0);
                json.put("ckmc",ckmc);
                json.put("shzt",0);
                json.put("shr","");
                json.put("dysj","");
                json.put("dyzt",0);
                json.put("shsj","");
            }
            if(hz.size()>0){
                json.put("hz",hz.get(0).getShow_hzid());
            }
            json.put("zdr",zdr);
            //预期到货通知行获取(未制作)
            List<Map<String,Object>> list = dao.getInfoDetailed(setAndModifyModel.getIds());
            //预期到货通知行获取(已制作)
            List<Map<String,Object>> listOld = dao.getByCgddid(setAndModifyModel.getIds());
            list.addAll(listOld);
            JSONArray arrsy = JSONArray.fromObject(list);
            if(arrsy.size()>0){
                json.put("list",arrsy);
            }
            //获取当前货主下 自动生成批次号，自动生成生产日期
            Map<String,Object> zdMap = dao.getZdByHzid(hz.get(0).getHzid());
            json.putAll(zdMap);
            return json;
        } catch (Exception e) {
            throw new ServiceException("获取新增需要的信息",e);
        }
    }

    @BaseServiceDescribe(moduleName = "预期到货通知单",btnName = "获取所有当前货主下供应商信息")
    public List<Map<String,Object>> getGysByHzid(String hzid) throws Exception{
        try {
            return dao.getGysByHzid(hzid);
        } catch (Exception e) {
            throw new ServiceException("获取所有当前货主下供应商信息",e);
        }
    }

    @BaseServiceDescribe(moduleName = "预期到货通知单",btnName = "获取所有当前货主下货品信息")
    public List<Map<String,Object>> getHpByHzid(String hzid) throws Exception{
        try {
            return dao.getHpByHzid(hzid);
        } catch (Exception e) {
            throw new ServiceException("获取所有当前货主下货品信息",e);
        }
    }

   /**
    * 查询（根据主键ID查询）
    * @param id 主键ID
    * @return WmsEstimatedArrivalOrder
    */
    public WmsEstimatedArrivalOrder baseSelectByPrimaryKey( String id ){
         return dao.baseSelectByPrimaryKey( id );
    }

   /**
    * 查询（根据ID 批量查询）
    * @param idList 主键ID列表
    * @return list
    */
    public Integer baseSelectBathPrimaryKeys( List<WmsEstimatedArrivalOrder> idList ){
         return dao.baseSelectBathPrimaryKeys( idList );
    }

    /**
     *修改 （匹配有值的字段）
     * @param entity 主键ID列表
     * @return int
     */
    @BaseServiceDescribe(moduleName = "预期到货通知单",btnName = "修改预期到货通知单")
    public void baseUpdateByPrimaryKeySelective( WmsEstimatedArrivalOrder entity )throws ServiceException,SucessException{
        Map<String,Object> map = dao.getPoidAsnztShzt(entity.getId());
        Integer asnCount = dao.getCountByAsnbh(entity.getAsnbh());
        if(entity.getAsnbh().equals(map.get("asnbh")) || (!entity.getAsnbh().equals(entity.getAsnbh()) && asnCount == 0)){
            if(map.get("asnzt").equals("3")){
                throw new ServiceException("此订单已作废不可修改");
            } else if(map.get("shzt").equals("1")){
                throw new ServiceException("此订单已审核不可修改");
            } else{
                Integer updateCount = dao.baseUpdateByPrimaryKeySelective( entity );
                if(updateCount>0){
                    throw new SucessException("修改预期到货通知单成功");
                }else{
                    throw new ServiceException("修改预期到货通知单失败，未插入数据库");
                }
            }
        }else{
            throw new ServiceException("修改预期到货通知单失败，ASN编号重复");
        }

    }

    /**
     * 删除预期到货通知单及明细
     * @param setAndModifyModel
     * @throws ServiceException
     * @throws SucessException
     */
    @BaseServiceDescribe(moduleName = "预期到货通知单",btnName = "作废预期到货通知单及明细")
    @Transactional
    public void del(SetAndModifyModel setAndModifyModel,String scr)throws SucessException,ServiceException{
        List<String> ids = setAndModifyModel.getIds();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("list",ids);
        map.put("scr",scr);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("scsj",sdf.format(new Date()));
        List<String> searchList = wmsEstimatedArrivalOrderDetailedMapper.delAsnSearch(ids);
        Integer count = dao.delAsn(map);
        Integer Detcount = 0;
        if(searchList.size()>0){
            Detcount = wmsEstimatedArrivalOrderDetailedMapper.delAsn(searchList);
        }
        if(count>0){
            throw new SucessException("作废预期到货通作废选择"+ids.size()+"条，成功"+count+"条,明细作废"+Detcount+"条");
        }else{
            throw new ServiceException("作废预期到货通作废选择"+ids.size()+"条，失败"+count+"条");
        }

    }

    /**
     * 收货完成预期到货通知单及明细
     * @param setAndModifyModel
     * @throws ServiceException
     * @throws SucessException
     */
    @BaseServiceDescribe(moduleName = "预期到货通知单",btnName = "收货完成预期到货通知单及明细")
    @Transactional
    public void fulfil(SetAndModifyModel setAndModifyModel,String xgr)throws SucessException,ServiceException{
        List<String> ids = setAndModifyModel.getIds();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("list",ids);
        map.put("xgr",xgr);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("xgsj",sdf.format(new Date()));
        List<String> searchList = wmsEstimatedArrivalOrderDetailedMapper.fulfilAsnSearch(ids);
        Integer count = dao.fulfilAsn(map);
        Integer Detcount = 0;
        if(searchList.size()>0){
            Detcount = wmsEstimatedArrivalOrderDetailedMapper.fulfilAsnDetailed(searchList);
        }
        //删除PDA收货任务  查询预期到货通知单对应的pda收货ids 然后删除主、子表
        List<String> pdas = wmsReceiptTaskPdaMapper.baseSelectByPrimaryYqid(ids);
        if(pdas.size()>0){
            wmsReceiptTaskPdaMapper.baseDeleteBathPrimaryYqids(ids);
            wmsReceiptTaskPdaDetailedMapper.baseDeleteBathPrimaryPdashids(pdas);
        }
        if(Detcount != 0){
            throw new SucessException("预期到货通知单收货完成选择"+ids.size()+"条，成功"+count+"条,明细完成"+Detcount+"条");
        } else{
            throw new ServiceException("预期到货通知单收货完成选择"+ids.size()+"条，失败"+ids.size()+"条,明细完成"+Detcount+"条");
        }

    }

    /**
     *预期到货通知单 审核
     * @param setAndModifyModel
     * @throws ServiceException
     * @throws SucessException
     */
    @BaseServiceDescribe(moduleName = "预期到货通知单",btnName = "审核预期到货通知单及明细")
    @Transactional
    public void auditing(SetAndModifyModel setAndModifyModel,String ddshr)throws ServiceException,SucessException{
        List<String> ids = null;
        ids = setAndModifyModel.getIds();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("list",ids);
        map.put("ddshr",ddshr);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("shenhsj",sdf.format(new Date()));
        Integer count =  dao.auditing(map);
        if(count == 0){
            throw new ServiceException("审核预期到货通知单失败");
        }else{
            throw new SucessException("审核预期到货通知单选择"+setAndModifyModel.getIds().size()+"条，成功"+count+"条");
        }
    }

    /**
    *修改（根据主键ID修改）
    * @param entity 主键ID列表
    * @return int
    */
    public Integer baseUpdateByPrimaryKey( WmsEstimatedArrivalOrder entity ){
         return dao.baseUpdateByPrimaryKey( entity );
    }

    @BaseServiceDescribe(moduleName = "预期到货通知单",btnName = "打印")
    public List<Map<String,Object>> print(Map<String,Object> map)throws ServiceException{
        try {
            List<Map<String,Object>> estimated = dao.print(map);
            for (Map<String, Object> stringObjectMap : estimated) {
                List<Map<String,Object>> detail = wmsEstimatedArrivalOrderDetailedMapper.print(stringObjectMap.get("id").toString());
                stringObjectMap.put("detail",detail);
            }
            return estimated;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("预期到货通知单获取打印信息失败");
        }
    }

    @BaseServiceDescribe(moduleName = "预期到货通知单",btnName = "生成质检单")
    @Transactional
    public void getBill(SetAndModifyModel setAndModifyModel,String sshzid,String ckid) throws SucessException,ServiceException{
            //成功总条数
            Integer sucessCount = 0;
            //失败单号信息
            StringBuffer failNumber = new StringBuffer();
            List<String> list = setAndModifyModel.getIds();
                for (String s : list) {
                    WmsEstimatedArrivalOrder wmsEstimatedArrivalOrder = dao.selectById(s);
                    //预期到货通知单ASN状态只有全部收货及收货完成可以生成质检单
                    if(wmsEstimatedArrivalOrder.getZjzt().equals("0") && (wmsEstimatedArrivalOrder.getAsnzt().equals("2") || wmsEstimatedArrivalOrder.getAsnzt().equals("4"))){
                        WmsOwner wmsOwner = wmsOwnerMapper.selectById(wmsEstimatedArrivalOrder.getHzid());
                        //判断当前货主的 质检方式不是 不质检 审核后状态为“已审核”。
                        if(!(wmsOwner.getZjfs().equals("0")) && wmsEstimatedArrivalOrder.getShzt().equals("1")){
                            WmsOwnerOrdertype wmsOwnerOrdertype = wmsOwnerOrdertypeMapper.selectById(wmsEstimatedArrivalOrder.getAsnlx());
                            //判断收发类别的质检规则是否需要质检
                            if(wmsOwnerOrdertype.getSfzj().equals("1")){
                                List<WmsEstimatedArrivalOrderDetailed> detailedList = wmsEstimatedArrivalOrderDetailedMapper.baseSelectBySsyqdid(s);
                                //质检单类型 判断质检单是否已创建，并且创建质检单ID
                                boolean wmsQualityTestingType = true;
                                WmsQualityInspectionList wmsQualityInspectionList = new WmsQualityInspectionList();
                                //遍历预期到货通知单明细
                                for (WmsEstimatedArrivalOrderDetailed wmsEstimatedArrivalOrderDetailed : detailedList) {
                                    //根据货品ID查询对应的质检规
                                    WmsQualityTesting wmsQualityTesting = wmsEstimatedArrivalOrderDetailedMapper.getQualityTesting(wmsEstimatedArrivalOrderDetailed.getHpid());
                                    if(null != wmsQualityTesting){
                                        //获取对应的质检规则明细
                                        WmsQualityTestingDetailed wmsQualityTestingDetailed = wmsEstimatedArrivalOrderDetailedMapper.getWmsQualityTestingDetailed(wmsQualityTesting.getId(),wmsEstimatedArrivalOrderDetailed.getSdsl());
                                        if(null != wmsQualityTestingDetailed){
                                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                            Date date = new Date();
                                            //ASN状态与ASN行状态改为“质检单创建”!!!!!!!!!!
                                            if(wmsQualityTestingType){
                                                //创建质检单相关信息
                                                wmsQualityInspectionList.setId(UUIDUtils.uuid());
                                                wmsQualityInspectionList.setSshzid(sshzid);
                                                wmsQualityInspectionList.setSsgysid(wmsEstimatedArrivalOrder.getGysid());
                                                //计算质检单号
                                                String number = String.valueOf(wmsEstimatedArrivalOrderDetailedMapper.getWmsQualityTestingCount(sshzid)+1);
                                                wmsQualityInspectionList.setZjdh(NumberProcessing.addZeroForNum(number,7));
                                                wmsQualityInspectionList.setAsnid(wmsEstimatedArrivalOrder.getId());
                                                wmsQualityInspectionList.setZt("0");
                                                wmsQualityInspectionList.setCjsj(sdf.format(date));
                                                wmsQualityInspectionList.setCkid(ckid);
                                                wmsQualityInspectionList.setCkrwzt(0);
                                                wmsQualityInspectionListMapper.insert(wmsQualityInspectionList);
                                                //修改预期到货通知单的质检状态为创建质检单
                                                wmsEstimatedArrivalOrder.setZjzt("1");
                                                dao.baseUpdateByPrimaryKeySelective(wmsEstimatedArrivalOrder);
                                                wmsQualityTestingType = false;
                                            }
                                            //创建质检单明细
                                            WmsQualityInspectionListDetailed wmsQualityInspectionListDetailed = new WmsQualityInspectionListDetailed();
                                            wmsQualityInspectionListDetailed.setId(UUIDUtils.uuid());
                                            wmsQualityInspectionListDetailed.setSszjdid(wmsQualityInspectionList.getId());
                                            if(wmsQualityTesting.getFs().equals("0")){
                                                wmsQualityInspectionListDetailed.setZjgzmxid("0");
                                            }else{
                                                wmsQualityInspectionListDetailed.setZjgzmxid(wmsQualityTestingDetailed.getId());
                                            }
                                            wmsQualityInspectionListDetailed.setHpid(wmsEstimatedArrivalOrderDetailed.getHpid());
                                            wmsQualityInspectionListDetailed.setYqsl(wmsEstimatedArrivalOrderDetailed.getYqsl());
                                            wmsQualityInspectionListDetailed.setPc(wmsEstimatedArrivalOrderDetailed.getHppc());
                                            wmsQualityInspectionListDetailed.setZt("0");
                                            wmsQualityInspectionListDetailed.setScrq(wmsEstimatedArrivalOrderDetailed.getScrq());
                                            wmsQualityInspectionListDetailed.setCkid(ckid);
                                            wmsQualityInspectionListDetailed.setYpsl(0);
                                            wmsQualityInspectionListDetailed.setAsnmxid(wmsEstimatedArrivalOrderDetailed.getId());
                                            //获取预期到货通知单明细预期数量
                                            Integer shsl = Integer.valueOf(wmsEstimatedArrivalOrderDetailed.getSdsl());
                                            switch (wmsQualityTesting.getFs()){
                                                //如果质检规则是全检
                                                case "0":
                                                    wmsQualityInspectionListDetailed.setYjsl(wmsEstimatedArrivalOrderDetailed.getShsl());
                                                    break;
                                                case "2":
                                                    //根据固定数量获取如果大于固定数量显示固定数量 如果小于则放入自身数量
                                                    Integer gdsl = Integer.valueOf(wmsQualityTestingDetailed.getGdsl());
                                                    if(shsl > gdsl){
                                                        wmsQualityInspectionListDetailed.setYjsl(String.valueOf(gdsl));
                                                    }else{
                                                        wmsQualityInspectionListDetailed.setYjsl(String.valueOf(shsl));
                                                    }
                                                    break;
                                                case "1":
                                                    //根据百分比生成
                                                    Double bfb = Double.valueOf(wmsQualityTestingDetailed.getBfb());
                                                    int num = (int)Math.ceil((shsl * bfb));
                                                    wmsQualityInspectionListDetailed.setYjsl(String.valueOf(num));
                                                    break;
                                                default:
                                                    break;
//                                                throw new  ServiceException("该明细对应的质检范围不存在");
                                            }
                                            //修改预期到货通知单明细的质检状态为创建质检单
                                            wmsEstimatedArrivalOrderDetailed.setZjzt("1");
                                            Integer addCount = wmsQualityInspectionListDetailedMapper.baseInsertSelective(wmsQualityInspectionListDetailed);
                                            wmsEstimatedArrivalOrderDetailedMapper.baseUpdateByPrimaryKeySelective(wmsEstimatedArrivalOrderDetailed);
                                            if(addCount>0){
                                                //成功条数+1
                                                sucessCount++;
                                            } else{
//                                            throw new ServiceException("生成质检单失败，未插入数据库");
                                                failNumber.append(wmsEstimatedArrivalOrder.getAsnbh());
                                                failNumber.append(" 未插入数据库,");
                                            }
                                        }else{
//                                        throw new  ServiceException("该明细对应的质检范围不存在");
                                            failNumber.append(wmsEstimatedArrivalOrder.getAsnbh());
                                            failNumber.append(" 该明细对应的质检范围不存在,");
                                        }
                                    }else{
//                                      throw new  ServiceException("货品对应的质检规则不存在");
                                        failNumber.append(wmsEstimatedArrivalOrder.getAsnbh());
                                        failNumber.append(" 货品对应的质检规则不存在,");
                                    }
                                }
                            }else{
//                                throw new  ServiceException("预期到货通知单“ASN类型”为不质检");
                                failNumber.append(wmsEstimatedArrivalOrder.getAsnbh());
                                failNumber.append(" 预期到货通知单“ASN类型”为不质检,");
                            }
                        }else{
//                            throw new  ServiceException("货主管理质检方式为“不质检”，或预期到货通知单审核状态“未审核”");
                            failNumber.append(wmsEstimatedArrivalOrder.getAsnbh());
                            failNumber.append(" 货主管理质检方式为“不质检”，或预期到货通知单审核状态“未审核,");
                        }
                    }else{
//                        throw new  ServiceException("预期到货通知单ASN状态只有“全部收货”及“收货完成”可以生成质检单");
                        failNumber.append(wmsEstimatedArrivalOrder.getAsnbh());
                        failNumber.append(" 预期到货通知单ASN状态只有“全部收货”、“未生成质检单”及“收货完成”可以生成质检单,");
                    }
                }
                if(sucessCount>0){
                    throw new SucessException("生成质检单选中"+setAndModifyModel.getIds().size()+"条，"+"成功"+sucessCount+"条," + (failNumber.length()>0 ? "单号："+failNumber.toString()+"失败。" : ""));
                }else{
                    throw new ServiceException("生成质检单选中"+setAndModifyModel.getIds().size()+"条，"+"失败"+setAndModifyModel.getIds().size()+"条，" + (failNumber.length()>0 ? "单号："+failNumber.toString()+"失败。" : ""));
                }


    }

}
